import CIcon, { iconList } from '@/components/CIcon/CIcon'
import CTextAreaForm from '@/components/CTextAreaForm/CTextAreaForm'
import IMenuVO from '@/model/vo/menu/IMenuVO'
import { routerOptionList } from '@/router/routerMap'
import useEffectRolePage from '@/useEffect/useEffectRolePage'
import { flatTree, listToTree } from '@/util/CommonUtil'
import { IconHelpCircle } from '@douyinfe/semi-icons'
import {
  Col,
  Form,
  Tooltip,
  Typography,
  useFormApi,
  useFormState,
} from '@douyinfe/semi-ui'
import { OptionProps } from '@douyinfe/semi-ui/lib/es/select'
import { TreeNodeData } from '@douyinfe/semi-ui/lib/es/tree'
import { useEffect, useState } from 'react'

// 获取 下拉选的数据
export function getMenuFormSelectData(modalVisible: boolean) {
  const { roleList } = useEffectRolePage(modalVisible)
  return { roleList }
}

interface IMenuFormItem {
  roleList: OptionProps[]
  menuTree: IMenuVO[]
  confirmLoading: boolean
}

export default function MenuFormItem(props: IMenuFormItem) {
  const formState = useFormState()
  const formApi = useFormApi()
  const [treeData, setTreeData] = useState<TreeNodeData[]>() // 上级菜单（树结构）

  useEffect(() => {
    if (props.menuTree) {
      // 先扁平化树结构
      const menuList = flatTree(
        props.menuTree,
        true,
        (item) => item.id !== formState.values.id // 不要本节点
      ).map((item) => ({
        id: item.id,
        key: item.id,
        value: item.id,
        label: item.name,
        parentId: item.parentId,
      })) as TreeNodeData[]

      // 再 listToTree
      setTreeData(listToTree(menuList))
    }
  }, [props.menuTree])

  return (
    <>
      <Col span={12}>
        <Form.TreeSelect
          field="parentId"
          showClear
          label="上级菜单"
          filterTreeNode
          showFilteredOnly
          treeData={treeData}
          className="w100"
          disabled={formState.values.authFlag}
          virtualize={{
            height: 300,
            itemSize: 28,
          }}
        ></Form.TreeSelect>
      </Col>
      <Col span={12}>
        <Form.Input
          field="name"
          rules={[
            {
              required: true,
              message: `请输入${
                formState.values.authFlag ? '权限名' : '菜单名'
              }`,
            },
          ]}
          showClear
          label={formState.values.authFlag ? '权限名' : '菜单名'}
        />
      </Col>
      {formState.values.authFlag ? (
        <>
          <Col span={12}>
            <Form.TextArea
              field="auths"
              autosize
              rows={2}
              showClear
              maxCount={255}
              rules={[
                {
                  required: true,
                  message: `请输入权限`,
                },
              ]}
              label={{
                text: '权限',
                extra: (
                  <Typography.Text
                    title="生成示例"
                    link={!props.confirmLoading}
                    onClick={() => {
                      if (props.confirmLoading) return
                      formApi.setValue(
                        'auths',
                        'menu:insertOrUpdate,menu:page,menu:deleteByIdSet,menu:infoById'
                      )
                    }}
                    disabled={props.confirmLoading}
                  >
                    生成示例
                  </Typography.Text>
                ),
              }}
            />
          </Col>
        </>
      ) : (
        <>
          <Col span={12}>
            <Form.Input
              field="path"
              showClear
              label={{
                text: '路径',
                extra: (
                  <Typography.Text
                    title="生成示例"
                    link={!props.confirmLoading}
                    onClick={() => {
                      if (props.confirmLoading) return
                      formApi.setValue('path', '/admin/dashboard/workplace')
                    }}
                    disabled={props.confirmLoading}
                  >
                    生成示例
                  </Typography.Text>
                ),
              }}
            />
          </Col>
          <Col span={12}>
            <Form.Select
              field="icon"
              showClear
              label="图标"
              filter={searchLabel}
              className="w100"
              virtualize={{ itemSize: 36 }}
            >
              {iconList.map((item) => (
                <Form.Select.Option value={item} key={item}>
                  <div className="flex ai-c">
                    <CIcon icon={item} className="m-r-10" /> {item}
                  </div>
                </Form.Select.Option>
              ))}
            </Form.Select>
          </Col>
          <Col span={12}>
            <Form.Switch
              field="showFlag"
              label={{
                text: '显示',
                extra: (
                  <Tooltip content="是否在左侧菜单栏显示">
                    <IconHelpCircle />
                  </Tooltip>
                ),
              }}
            />
          </Col>
          <Col span={12}>
            <Form.Switch
              field="firstFlag"
              label={{
                text: '起始页',
                extra: (
                  <Tooltip content="是否为默认打开的页面">
                    <IconHelpCircle />
                  </Tooltip>
                ),
              }}
            />
          </Col>
        </>
      )}
      <Col span={12}>
        <Form.Select
          multiple
          field="roleIdSet"
          showClear
          label="绑定角色"
          filter
          className="w100"
          optionList={props.roleList}
          maxTagCount={10}
        ></Form.Select>
      </Col>
      <Col span={12}>
        <Form.InputNumber
          showClear
          className="w100"
          field="orderNo"
          label="排序号"
        />
      </Col>
      <Col span={12}>
        <Form.Switch field="enableFlag" label="启用" />
      </Col>
      {!formState.values.authFlag && (
        <Col span={12}>
          <Form.Switch
            field="linkFlag"
            label={{
              text: '外链',
              extra: (
                <Tooltip content="如果开启，打开页面时，会在一个新的窗口打开此页面">
                  <IconHelpCircle />
                </Tooltip>
              ),
            }}
          />
        </Col>
      )}
      <Col span={12}>
        <CTextAreaForm></CTextAreaForm>
      </Col>
      {!formState.values.linkFlag && !formState.values.authFlag && (
        <Col span={12}>
          <Form.Select
            field="router"
            showClear
            filter
            className="w100"
            label="路由"
            optionList={routerOptionList}
          />
        </Col>
      )}
    </>
  )
}

// 搜索自定义 select模板
export function searchLabel(sugInput: string, option: OptionProps) {
  let label = String(option.value).toUpperCase()
  let sug = sugInput.toUpperCase()
  return label.includes(sug)
}
